package com.java.study.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.java.study.common.utils.OKHttpUtil;
import com.java.study.config.WechatConfig;
import com.java.study.entity.VideoOrderEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.study.common.utils.PageUtils;
import com.java.study.common.utils.Query;

import com.java.study.dao.UserDao;
import com.java.study.entity.UserEntity;
import com.java.study.service.UserService;
import org.springframework.transaction.annotation.Transactional;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<UserEntity> page = this.page(
				new Query<UserEntity>().getPage(params),
				new QueryWrapper<UserEntity>()
		);

		return new PageUtils(page);
	}

    @Autowired
    private WechatConfig wechatConfig;

    @Override
	@Transactional
    public UserEntity saveWeChatUser(String code) {

        String accessTokenUrl = String.format(WechatConfig.OPEN_ACCESS_TOKEN_URL,wechatConfig.getOpenAppid(),wechatConfig.getOpenAppsecret(),code);

        //通过code获取access_token
        Map<String ,Object> baseMap =  OKHttpUtil.httpGet(accessTokenUrl);

        if(MapUtil.isEmpty(baseMap)){ return  null; }
        String accessToken = (String)baseMap.get("access_token");
        String openId  = (String)baseMap.get("openid");

        //查询数据库,判断用户是否已经注册
		UserEntity dbUser = this.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getOpenid, openId));
		if (dbUser!=null){
			return dbUser;
		}

		//通过access_token获取用户基本信息
        String userInfoUrl = String.format(WechatConfig.OPEN_USER_INFO_URL,accessToken,openId);
		baseMap =  OKHttpUtil.httpGet(userInfoUrl);

		if(MapUtil.isEmpty(baseMap)){ return  null; }
        String nickname = (String)baseMap.get("nickname");
        Integer sex  = (Integer) baseMap.get("sex");
        String province = (String)baseMap.get("province");
        String city = (String)baseMap.get("city");
        String country = (String)baseMap.get("country");
        String headimgurl = (String)baseMap.get("headimgurl");
		StringBuilder sb = new StringBuilder(country).append("|").append(province).append("|").append(city);
		String finalAddress = sb.toString();
		try {
			//解决乱码
			nickname = new String(nickname.getBytes("ISO-8859-1"), "UTF-8");
			finalAddress = new String(finalAddress.getBytes("ISO-8859-1"), "UTF-8");

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		UserEntity user = new UserEntity();
		user.setName(nickname);
		user.setHeadImg(headimgurl);
		user.setCity(finalAddress);
		user.setOpenid(openId);
		user.setSex(sex);
		user.setCreateTime(new Date());
		this.save(user);
        return user;
    }

}